package jude.java.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

public class WebUtils {
	
	public static HttpClient getHttpClient() {
		HttpClient client = new DefaultHttpClient();
		HttpParams params = client.getParams();
		params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, Boolean.TRUE);
		params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
		return client;
	}
	
	public static void setFollowRedirects(HttpGet get, Boolean b) {
		get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, b);
	}
	
	public static void pretendRequestHeader(HttpMethodBase method) {
		method.addRequestHeader("accept", "*/*");
		method.addRequestHeader("accept-language", "en-US,en-GB;q=0.5");		//zh-cn
		method.addRequestHeader("ua-cpu", "x86");
//		method.addRequestHeader("accept-encoding", "gzip, deflate");
		method.addRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; FDM; Tablet PC 2.0)");
//		method.addRequestHeader("host", "localhost:8080");
		method.addRequestHeader("connection", "Keep-Alive");
//		method.addRequestHeader("cookie", "");
	}
	
	public static void pretendRequestHeader(HttpRequestBase method) {
		method.addHeader("accept", "*/*");
		method.addHeader("accept-language", "en-US,en-GB;q=0.5");		//zh-cn
		method.addHeader("ua-cpu", "x86");
//		method.addHeader("accept-encoding", "gzip, deflate");
		method.addHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; FDM; Tablet PC 2.0)");
//		method.addHeader("host", "localhost:8080");
		method.addHeader("connection", "Keep-Alive");
//		method.addHeader("cookie", "");
	}
	
	public static String getResponse(HttpMethodBase method, int max, String encode) throws IOException {
		StringBuilder sb = new StringBuilder();
		Reader reader = new InputStreamReader(method.getResponseBodyAsStream(), encode);
		char[] buffer = new char[4096];
		int n, left = max > 0 ? max : Integer.MAX_VALUE;
		while (left > 0 && (n = reader.read(buffer, 0, Math.min(buffer.length, left))) != -1) {
			if (n == 0)
				continue;
			left -= n;
			sb.append(buffer, 0, n);
		}
		return sb.toString();
	}
	public static String getResponse(HttpResponse response, int max, String encode) throws IOException {
		StringBuilder sb = new StringBuilder();
		Reader reader = new InputStreamReader(response.getEntity().getContent(), encode);
		char[] buffer = new char[4096];
		int n, left = max > 0 ? max : Integer.MAX_VALUE;
		while (left > 0 && (n = reader.read(buffer, 0, Math.min(buffer.length, left))) != -1) {
			if (n == 0)
				continue;
			left -= n;
			sb.append(buffer, 0, n);
		}
		return sb.toString();
	}
	
	//Set-Cookie:sessionID=1283000444272990000; domain=.goarticles.com; path=/; expires=Mon, 27-Sep-2010 13:00:44 GMT
	public static String getCookies(HttpMethodBase method) {
		Header h = method.getResponseHeader("Set-Cookie");
		if (h == null)
			return null;
		String value = h.getValue();
		if (StringUtils.isEmpty(value))
			return null;
		String[] ss = value.split(";");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < ss.length; i++) {
			String[] s = StringUtils.split(ss[i].trim(), "=", 2);
			if (s.length != 2)
				continue;
			if (s[0].equals("domain") || s[0].equals("path") || s[0].equals("expires"))
				continue;
			if (sb.length() > 0)
				sb.append("; ");
			sb.append(ss[i]);
		}
		return sb.length() > 0 ? sb.toString() : null;
	}
	
	public static void showResponseHeader(HttpMethodBase method) {
		Header[] headers = method.getResponseHeaders();
		if (headers == null)
			return;
		for (int i = 0; i < headers.length; i++) {
			Header h = headers[i];
			System.out.println(h.getName()+"="+h.getValue());
		}
	}


	/**
	 * ftp://name:pwd@192.168.73.170/data/hebjh/pj.txt
	 * */
	public static String[] parseFtpPath(String ftpPath) {
		if(ftpPath == null)
			return null;
		ftpPath = ftpPath.trim();
		if (ftpPath.length() < 6 || !ftpPath.substring(0, "ftp://".length()).equalsIgnoreCase("ftp://"))
			return null;
		String regexp = "^ftp://(?:(.+)(?::(.*))@)?([^/:]*)(?::(\\d+))?(.*)$";
		Pattern p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(ftpPath);
		if(m.find()) {
			//m.groupCount === 5
			String usr = m.group(1) == null ? "anonymous" : m.group(1);
			String pwd = m.group(2) == null ? "" : m.group(2);
			String ip  = m.group(3);
			String port = m.group(4) == null ? "21" : m.group(4);
			String path = m.group(5) == null ? "/" : m.group(5);
			return new String[] {ip, usr, pwd, port, path};
		}
		return null;
	}
	
}
